package com.yycx.app.provider.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.handler.AppProxyHandler;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.mybatis.model.ResultBody;
import com.yycx.common.utils.ApiAssert;
import com.yycx.common.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author zyf
 */
@Api(tags = "代理接口服务")
@RestController
public class AppProxyController {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired(required = false)
    private AppProxyHandler appProxyHandler;

    /**
     * 代理请求
     *
     * @param params
     * @return
     */
    @ApiOperation(value = "代理请求", notes = "代理请求")
    @PostMapping("/proxyUrl")
    public ResultBody proxyUrl(@RequestParam(required = false) Map params) {
        EntityMap paramsMap = new EntityMap(params);
        Object url = params.get("url");
        ApiAssert.isNotEmpty("url不能为空", url);
        params.remove("url");
        if (FlymeUtils.isNotEmpty(appProxyHandler)) {
            ResultBody resultBody = appProxyHandler.validate(url.toString(), paramsMap);
            if (!resultBody.isOk()) {
                return resultBody;
            }
        }
        EntityMap map = redisUtils.getConfigMap("XUANKE");
        String access_token = map.get("accessToken");
        ApiAssert.isNotEmpty("accessToken未配置", access_token);
        HttpResponse response = HttpRequest.post(url.toString())
                .form(params)
                .header("Authorization", access_token)
                .timeout(8000)
                .execute();
        String result = response.body();
        JSONObject obj = new JSONObject();
        if (FlymeUtils.isNotEmpty(result)) {
            obj = JSONObject.parseObject(result);
        }
        if (FlymeUtils.isNotEmpty(appProxyHandler)) {
            appProxyHandler.complete(url.toString(), paramsMap);
        }

        return ResultBody.ok("", obj);
    }


}
